import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

part_head_router = APIRouter(prefix="/part/partHead", tags=["备件入库管理"], dependencies=[Depends(oauth2_scheme)])


class SparePartInboundSearch(PaginationBase):
    # 筛选条件
    fsiteNo: Optional[str] = Field("", description="站点编号")
    ftakedateStart: Optional[str] = Field("", description="入库日期开始(yyyyMMdd)")
    ftakedateEnd: Optional[str] = Field("", description="入库日期结束(yyyyMMdd)")
    fbillno: Optional[str] = Field("", description="单据编号(支持前缀匹配)")
    fbillstate: Optional[str] = Field("", description="单据状态")


@part_head_router.get("/list", summary="")
def list_part(search: SparePartInboundSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from lims.s_tc_part_head where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fbillno != "":
        sql = sql + " and fbillno like concat('%', :fbillno ,'%')"
        param["fbillno"] = search.fbillno
    if search.fbillstate != "":
        sql = sql + " and fbillstate = :fbillstate "
        param["fbillstate"] = search.fbillstate
    if (search.ftakedateStart != "") and (search.ftakedateEnd != ""):
        sql = sql + " and to_char(forddate,'yyyymmdd') between :ftakedateStart and :ftakedateEnd "
        param["ftakedateStart"] = search.ftakedateStart
        param["ftakedateEnd"] = search.ftakedateEnd
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fbillno,forduser,forddate,frecdate,fsupno,fitemcount,fpiececount,ftotalamt,"
    sql = sql + " fsrcbillno,fexplanation,fupddate,foperator,fcheckdate,fcheckuser,fbillstate"
    sql = sql + " from lims.s_tc_part_head where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fbillno != "":
        sql = sql + " and fbillno like concat('%', :fbillno ,'%')"
        param["fbillno"] = search.fbillno
    if search.fbillstate != "":
        sql = sql + " and fbillstate = :fbillstate "
        param["fbillstate"] = search.fbillstate
    if (search.ftakedateStart != "") and (search.ftakedateEnd != ""):
        sql = sql + " and to_char(forddate,'yyyymmdd') between :ftakedateStart and :ftakedateEnd "
        param["ftakedateStart"] = search.ftakedateStart
        param["ftakedateEnd"] = search.ftakedateEnd
    if search.order == "desc":
        sql = sql + " order by  forddate,fbillno desc "
    else:
        sql = sql + " order by  forddate,fbillno "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    # details 明细列表
    param = {}
    sql_3 = " select b.fbillno,b.fline,b.fpartid,b.fbuyprice,b.fqty,b.ftotamt,b.fmemo"
    sql_3 = sql_3 + " from lims.s_tc_part_head a,lims.s_tc_part_detail b where a.fbillno=b.fbillno "
    if search.fsiteNo != "":
        sql_3 = sql_3 + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fbillno != "":
        sql_3 = sql_3 + " and a.fbillno like concat('%', :fbillno ,'%')"
        param["fbillno"] = search.fbillno
    if search.fbillstate != "":
        sql_3 = sql_3 + " and fbillstate = :fbillstate "
        param["fbillstate"] = search.fbillstate
    if (search.ftakedateStart != "") and (search.ftakedateEnd != ""):
        sql_3 = sql_3 + " and to_char(forddate,'yyyymmdd') between :ftakedateStart and :ftakedateEnd "
        param["ftakedateStart"] = search.ftakedateStart
        param["ftakedateEnd"] = search.ftakedateEnd
    sql_3 = sql_3 + " order by b.fbillno,b.fline"
    data_detail = db.execute(text(sql_3), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fbillno'] = data[key][0]
        d1['forduser'] = data[key][1]
        d1['forddate'] = data[key][2]
        d1['frecdate'] = data[key][3]
        d1['fsupno'] = data[key][4]
        d1['fitemcount'] = data[key][5]
        d1['fpiececount'] = data[key][6]
        d1['ftotalamt'] = data[key][7]
        d1['fsrcbillno'] = data[key][8]
        d1['fexplanation'] = data[key][9]
        d1['fupddate'] = data[key][10]
        d1['foperator'] = data[key][11]
        d1['fcheckdate'] = data[key][12]
        d1['fcheckuser'] = data[key][13]
        d1['fbillstate'] = data[key][14]
        sbillno = data[key][0]

        detail_list = []
        for j1 in range(len(data_detail)):
            if (str(data_detail[j1][0]) == str(sbillno)):
                d2 = {}
                d2['fbillno'] = data_detail[j1][0]
                d2['fline'] = data_detail[j1][1]
                d2['fpartid'] = data_detail[j1][2]
                d2['fbuyprice'] = data_detail[j1][3]
                d2['fqty'] = data_detail[j1][4]
                d2['ftotamt'] = data_detail[j1][5]
                d2['fmemo'] = data_detail[j1][6]
                detail_list.append(d2)

        d1["details"] = detail_list
        data_list.append(d1)
    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class SparePartInboundDetailCreate(BaseModel):
    """备件入库明细新增参数"""
    fline: int = Field(..., description="行号")
    fpartid: str = Field(..., description="备件ID")
    fbuyprice: float = Field(..., description="购买单价")
    fqty: float = Field(..., description="数量")
    ftotamt: float = Field(..., description="总金额")
    fmemo: Optional[str] = Field("", description="备注")


class SparePartInboundCreate(BaseModel):
    """备件入库新增请求参数"""
    fbillno: str = Field(..., description="单据编号")
    forduser: str = Field(..., description="制单人ID")
    forddate: str = Field(..., description="制单日期(格式需与数据库存储一致)")
    frecdate: str = Field(..., description="入库日期(格式需与数据库存储一致)")
    fsupno: str = Field(..., description="供应商编号")
    fbillstate: int = Field(..., description="单据状态编码")
    fupddate: str = Field(..., description="更新日期(格式需与数据库存储一致)")
    foperator: str = Field(..., description="操作人ID")
    fexplanation: Optional[str] = Field("", description="备注说明")
    details: List[SparePartInboundDetailCreate] = Field(..., description="入库明细列表")


@part_head_router.post("/create", summary="备件入库新增接口")
def create_part_inbound(create: SparePartInboundCreate, db: Session = Depends(get_db)):
    try:
        fitemcount = 0
        fpiececount = 0
        ftotalamt = 0
        fbillno = create.fbillno
        # 返回内容
        detail_list = []
        with db.begin():
            details = create.details
            for detail in details:
                sql = "insert into lims.s_tc_part_detail(fbillno,fline,fpartid,fbuyprice,fqty,ftotamt,fmemo)"
                sql = sql + " values( :fbillno , :fline , :fpartid , :fbuyprice , :fqty , :ftotamt , :fmemo )"
                db.execute(text(sql), {
                    "fbillno": fbillno,
                    "fline": detail.fline,
                    "fpartid": detail.fpartid,
                    "fbuyprice": detail.fbuyprice,
                    "fqty": detail.fqty,
                    "ftotamt": detail.ftotamt,
                    "fmemo": detail.fmemo
                })
                fitemcount = fitemcount + 1
                fpiececount = fpiececount + detail.fqty
                ftotalamt = ftotalamt + detail.ftotamt

                # 返回明细
                d2 = {}
                d2['fbillno'] = fbillno
                d2['fline'] = detail.fline
                d2['fpartid'] = detail.fpartid
                d2['fbuyprice'] = detail.fbuyprice
                d2['fqty'] = detail.fqty
                d2['ftotamt'] = detail.ftotamt
                d2['fmemo'] = detail.fmemo
                detail_list.append(d2)
            sql = "insert into lims.s_tc_part_head(fbillno,forduser,frecdate,forddate,fsupno,fitemcount,fpiececount,ftotalamt,fexplanation,fupddate,foperator,fbillstate)"
            sql = sql + " values( :fbillno , :forduser , :frecdate , :forddate , :fsupno , :fitemcount , :fpiececount , :ftotalamt , :fexplanation , :fupddate , :foperator , :fbillstate )"
            db.execute(text(sql), {
                "fbillno": fbillno,
                "forduser": create.forduser,
                "frecdate": create.frecdate,
                "forddate": create.forddate,
                "fsupno": create.fsupno,
                "fitemcount": fitemcount,
                "fpiececount": fpiececount,
                "ftotalamt": ftotalamt,
                "fexplanation": create.fexplanation,
                "fupddate": create.fupddate,
                "foperator": create.foperator,
                "fbillstate": create.fbillstate,
            })
            # 返回
            d1 = {}
            d1['fbillno'] = fbillno
            d1['forddate'] = create.forddate
            d1['frecdate'] = create.frecdate
            d1['forduser'] = create.forduser
            d1['fsupno'] = create.fsupno
            d1['fitemcount'] = fitemcount
            d1['fpiececount'] = fpiececount
            d1['ftotalamt'] = float(ftotalamt)
            d1['fsrcbillno'] = ""
            d1['fexplanation'] = create.fexplanation
            d1['fupddate'] = create.fupddate
            d1['foperator'] = create.forduser
            d1['fcheckdate'] = None
            d1['fcheckuser'] = None
            d1['fbillstate'] = create.fbillstate
            d1["details"] = detail_list
            return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@part_head_router.post("/update", summary="备件入库修改接口")
def update_part_inbound(update: SparePartInboundCreate, db: Session = Depends(get_db),
                        token: str = Depends(oauth2_scheme)):
    try:
        fitemcount = 0
        fpiececount = 0
        ftotalamt = 0
        fbillno = update.fbillno
        fbillstate = update.fbillstate
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            if (fbillstate == 8):
                sql = "update lims.s_tc_part_head "
                sql = sql + " set fbillstate=8,fcheckdate=now(),fcheckuser= :userid "
                sql = sql + " where fbillno= :fbillno "
                db.execute(text(sql), {
                    "userid": user_id,
                    "fbillno": fbillno,
                })
            else:
                sql = "delete from lims.s_tc_part_detail where fbillno= :fbillno "
                db.execute(text(sql), {
                    "fbillno": fbillno,
                })

                details = update.details
                for detail in details:
                    sql = "insert into lims.s_tc_part_detail(fbillno,fline,fpartid,fbuyprice,fqty,ftotamt,fmemo)"
                    sql = sql + " values( :fbillno , :fline , :fpartid , :fbuyprice , :fqty , :ftotamt , :fmemo )"
                    db.execute(text(sql), {
                        "fbillno": fbillno,
                        "fline": detail.fline,
                        "fpartid": detail.fpartid,
                        "fbuyprice": detail.fbuyprice,
                        "fqty": detail.fqty,
                        "ftotamt": detail.ftotamt,
                        "fmemo": detail.fmemo
                    })
                    fitemcount = fitemcount + 1
                    fpiececount = fpiececount + detail.fqty
                    ftotalamt = ftotalamt + detail.ftotamt
                sql = "update lims.s_tc_part_head "
                sql = sql + " set forddate= :forddate ,forduser= :forduser ,fexplanation= :fexplanation "
                sql = sql + ",fsupno= :fsupno ,frecdate= :frecdate "
                sql = sql + ",fitemcount= :fitemcount ,fpiececount= :fpiececount ,ftotalamt= :ftotalamt "
                sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
                sql = sql + " where fbillno= :fbillno "
                db.execute(text(sql), {
                    "forddate": update.forddate,
                    "forduser": update.forduser,
                    "fexplanation": update.fexplanation,
                    "fsupno": update.fsupno,
                    "frecdate": update.frecdate,
                    "fitemcount": fitemcount,
                    "fpiececount": fpiececount,
                    "ftotalamt": ftotalamt,
                    "fupddate": update.fupddate,
                    "foperator": update.foperator,
                    "fbillno": fbillno,
                })
        return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
